<template>
  <el-button @click="show = true" class="upload-data-button">{{ title }}</el-button>
  <a-dialog v-model="show" :title="title" :confirm="handleUploadConfirm" :width="600" confirmText="导入">
    <a-form ref="uploadElement" v-model="uploadForm" :list="uploadList"></a-form>
    <div class="sysm">
      <div class="sysm-title">使用说明</div>
      <div class="sysm-item">1.每次上传数据条数限制为10000条，超出部分不导入</div>
      <div class="sysm-item">2.导入不成功的记录会在结果中反馈</div>
      <div class="sysm-item">3.标题行不会被导入</div>
      <div class="sysm-item">4.上传成功后，数据将被展示，请确保数据准确</div>
      <div class="sysm-item">5.上传数据量大小会影响上传时间(大约需要3-5分钟),请耐心等待</div>
    </div>
  </a-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

defineOptions({
  name: 'a-upload-data'
})

interface Props {
  confirm: (formData: FormData, close: () => void) => void
  title?: string
}

const show = ref(false)
const props = withDefaults(defineProps<Props>(), {
  title: '批量导入'
})

const uploadElement = ref<AFormInstance | null>()
const limit = 1
const uploadForm = ref({
  upload: [] as UploadFiles
})
const uploadList = ref<FormItem[]>([
  {
    prop: 'upload',
    'aria-label': '模版上传',
    type: 'upload',
    'http-request': () => {
      return uploadElement.value?.element.validateField('upload')
    },
    'on-remove': async () => {
      uploadElement.value?.element.resetFields('upload')
    },
    rules: [
      {
        required: true,
        validator(_: unknown, value: { name: string }[], callback: (result?: Error) => void) {
          if (value && value.length > limit) {
            callback(new Error('最多上传' + limit + '个文件'))
          } else if (value && value.length && !new RegExp(/\.(xlsx|xls)$/).test(value[value.length - 1]!.name)) {
            callback(new Error('请上传表格文件'))
          } else if (!value || !value.length) {
            callback(new Error('请上传文件'))
          } else {
            callback()
          }
        }
      }
    ]
  }
])

function handleUploadConfirm() {
  uploadElement.value?.element.validate((valid: boolean) => {
    if (valid) {
      const formData = new FormData()
      formData.append('file', uploadForm.value.upload[0]!.raw as File)
      props.confirm(formData, () => {
        show.value = false
      })
    }
  })
}

watch(
  () => show.value,
  () => {
    uploadForm.value.upload = []
  }
)
</script>

<style lang="scss">
.upload-data-button {
  margin-right: 12px;
}
.sysm {
  margin-top: 50px;
  &-title {
    font-size: $font-size;
    font-weight: bold;
    margin-bottom: $margin;
  }
  &-item {
    color: red;
    font-size: $font-size-small;
    margin-bottom: $margin-small;
  }
}
</style>
